﻿<%@ WebHandler Language="C#" Class="CustomObjectMaint" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

/**
 * Description: 自定义对象维护
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * create Date:2023-01-16
 */

public class CustomObjectMaint : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "getData":
                    getData(context);
                    break;
                case "insertData":
                    insertData(context);//添加
                    break;
                case "updateData":
                    updateData(context);//更新
                    break;
                case "deleteData":
                    deleteData(context);//删除
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    //查询已维护数据
    void getData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            string sql = @"
SELECT t.customobjectid,t.customobjectname,t.customobjectdesc,e.fullname creater,t.createdate,e2.fullname updater,t.lastchangedate,
       t.isuse,SUM(DECODE(td.customobjectitemsid,NULL,0,1)) useqty
FROM customobject t
LEFT JOIN customobjectitems td ON td.customobjectid = t.customobjectid
LEFT JOIN employee e ON e.employeeid = t.createemployeeid
LEFT JOIN employee e2 ON e2.employeeid = t.lastchangeemployeeid
WHERE 1=1";
            //对象名称
            if (context.Request["customobjectname"] != null && context.Request["customobjectname"].ToString() != "")
            {
                sql += string.Format(" AND t.customobjectname LIKE '%{0}%'", context.Request["customobjectname"].ToString());
            }

            //创建人
            if (context.Request["creater"] != null && context.Request["creater"].ToString() != "")
            {
                sql += string.Format(" AND e.fullname LIKE '%{0}%'", context.Request["creater"].ToString());
            }

            //创建时间
            if (context.Request["createdateStart"] != null && context.Request["createdateStart"].ToString() != "")
            {
                sql += string.Format(" AND t.createdate >= to_date('{0} 00:00:00','yyyy/mm/dd hh24:mi:ss')", context.Request["createdateStart"].ToString());
            }
            if (context.Request["createdateEnd"] != null && context.Request["createdateEnd"].ToString() != "")
            {
                sql += string.Format(" AND t.createdate <= to_date('{0} 23:59:59','yyyy/mm/dd hh24:mi:ss')", context.Request["createdateEnd"].ToString());
            }

            //启用状态
            if (context.Request["isuse"] != null && context.Request["isuse"].ToString() != "全部")
            {
                sql += string.Format(" AND t.isuse = '{0}'", context.Request["isuse"].ToString());
            }

            sql += @"
GROUP BY t.customobjectid,t.customobjectname,t.customobjectdesc,e.fullname,t.createdate,e2.fullname,t.lastchangedate,
         t.isuse
";
            uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
            paraPage.CurrentPageIndex = Convert.ToInt32(context.Request.Form["pageNumber"].ToString());//页码
            paraPage.PageSize = Convert.ToInt32(context.Request.Form["PageSize"].ToString());//每页页数
            paraPage.strSQL = sql;
            uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
            foreach (DataColumn col in result.DBTable.Columns)
            {
                col.ColumnName = col.ColumnName.ToLower();
            }
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    //插入
    void insertData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            string customObjectName = context.Request.Form["customObjectName"].ToString();//对象名称
            string sql = string.Format("select * from customobject t where t.customobjectname = '{0}'", customObjectName);
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dt.Rows.Count > 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "添加失败，对象名称【" + customObjectName + "】已存在!", DBTable = null }));
            }
            else
            {
                string customObjectDesc = context.Request.Form["customObjectDesc"].ToString();//对象描述
                string isuse = context.Request.Form["isuse"].ToString();//启用状态
                string createemployeeid = m_UserInfo.EmployeeID.ToString();//创建人
                sql = @"
INSERT INTO customobject(customobjectid,customobjectname,customobjectdesc,createemployeeid,createdate,isuse)
VALUES('{0}','{1}','{2}','{3}',sysdate,'{4}')";

                sql = string.Format(sql, Guid.NewGuid().ToString(),//唯一id
                                         customObjectName,//对象名称
                                         customObjectDesc,//对象描述
                                         createemployeeid,//创建人
                                         isuse);
                int insertResult = DatabaseHelper.ExecuteSql(sql);
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
            }
        }
    }

    //更新
    void updateData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            string customObjectId = context.Request.Form["customObjectId"].ToString();//对象唯一id
            string customObjectName = context.Request.Form["customObjectName"].ToString();//对象名称
            string customObjectDesc = context.Request.Form["customObjectDesc"].ToString();//对象描述
            string isuse = context.Request.Form["isuse"].ToString();//启用状态
            string lastchangeemployeeid = m_UserInfo.EmployeeID.ToString();//更新人
            string sql = string.Format("SELECT t.customobjectname FROM customobject t WHERE t.customobjectid = '{0}'", customObjectId);
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dt.Rows[0]["customobjectname"].ToString() == customObjectName)//将要修改的对象名称和原来保持一致时
            {
                
                sql = @"
UPDATE customobject t SET t.customobjectdesc = '{0}',t.lastchangeemployeeid='{1}',t.lastchangedate = SYSDATE,t.isuse = {2} WHERE t.customobjectid = '{3}'";
                sql = string.Format(sql, customObjectDesc,//对象描述
                                         lastchangeemployeeid,//更新人
                                         isuse,//是否启用
                                         customObjectId);//对象唯一id
                int insertResult = DatabaseHelper.ExecuteSql(sql);
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
            }
            else
            {
                sql = string.Format("SELECT t.customobjectname FROM customobject t WHERE t.customobjectname = '{0}'", customObjectName);
                dt = DatabaseHelper.Query_ReturnDatTable(sql);
                if (dt.Rows.Count > 0)//将要修改后的对象名称已存在时
                {
                    context.Response.Write(
                        JsonConvert.SerializeObject(
                            new uMESProcessResult()
                            {
                                Result = false,
                                Message = "更新失败，对象名称【" + customObjectName + "】已存在!",
                                DBTable = null
                            }
                        )
                    );
                }
                else
                {
                    sql = @"
UPDATE customobject t SET t.customobjectname = '{0}',t.customobjectdesc = '{1}',t.lastchangeemployeeid='{2}',t.lastchangedate = SYSDATE,t.isuse = {3} WHERE t.customobjectid = '{4}'";
                    sql = string.Format(sql, customObjectName,//对象名称
                                             customObjectDesc,//对象描述
                                             lastchangeemployeeid,//更新人
                                             isuse,//isuse
                                             customObjectId);//对象唯一id
                    int insertResult = DatabaseHelper.ExecuteSql(sql);
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
                }
            }
        }
    }

    //删除
    void deleteData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            string customObjectId = context.Request.Form["customObjectId"].ToString();//对象唯一id
            string customObjectName = context.Request.Form["customObjectName"].ToString();//对象名称
            string sql = string.Format("SELECT * FROM customobjectitems t WHERE t.customobjectid = '{0}'", customObjectId);
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dt.Rows.Count > 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "删除失败，对象名称【" + customObjectName + "】存在子项，不能删除!", DBTable = null }));
            }
            else
            {
                sql = string.Format(@"DELETE customobject t WHERE t.customobjectid = '{0}'", customObjectId);//对象唯一id
                int insertResult = DatabaseHelper.ExecuteSql(sql);
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
            }
        }
    }
}